package com.sto.stoapp.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.Vibrator;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.sto.stoapp.StoConfig;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.StoLoginActivity;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.BillcodeManager;
import com.sto.stoapp.db.manager.CastManager;
import com.sto.stoapp.db.manager.ErrorRecordManager;
import com.sto.stoapp.db.manager.LoginInfoManager;
import com.sto.stoapp.db.manager.NextSiteManager;
import com.sto.stoapp.db.manager.OrderReturnReasonManager;
import com.sto.stoapp.db.manager.OrgRuleManager;
import com.sto.stoapp.db.manager.ProblemManager;
import com.sto.stoapp.db.manager.RouteManager;
import com.sto.stoapp.db.manager.SalesManager;
import com.sto.stoapp.db.manager.SalesSignNameManager;
import com.sto.stoapp.db.manager.ServerSmsManager;
import com.sto.stoapp.db.manager.SiteFullManager;
import com.sto.stoapp.db.manager.UserInfoManager;
import com.sto.stoapp.db.manager.UserManager;
import com.sto.stoapp.db.manager.UserRuleManager;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.widget.BaseDialog;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;


/**
 * 辅助类
 *
 * @author mgf
 */
@SuppressLint("ShowToast")
public class Helper {

    private static final String DATEFORMAT_PACKET = "yyyyMMddHHmmss";

    /**
     * 显示一个LENGTH_SHORT Toast
     *
     * @param context 上下文
     * @param content 内容
     */
    public static void showToast(Context context, String content) {
        if (content != null && !content.equals(""))
            Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
    }

    /**
     * 显示一个LENGTH_LONG Toast
     *
     * @param context 上下文
     * @param content 内容
     */
    public static void showLongToast(Context context, String content) {
        if (content != null && !content.equals(""))
            Toast.makeText(context, content, Toast.LENGTH_LONG).show();
    }
    static Toast mToast;
    /**
     * 显示Toast
     */
    public static void showCanHideToast(Context context, String content, int duration) {
        if (mToast == null) {
            mToast = Toast.makeText(context, content, duration);
            mToast.show();
        } else {
            mToast.setText(content);
            mToast.setDuration(duration);
            mToast.show();
        }
    }
    /**
     * 带有声音显示的Toast
     *
     * @param context   上下文
     * @param content   内容
     * @param soundType 声音类型
     */
    public static void showSoundToast(Context context, String content,
                                      boolean soundType) {
        Vibrator vibtor = (Vibrator) context
                .getSystemService(Service.VIBRATOR_SERVICE);
        if (content != null && !content.equals("")) {
            Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
            if (soundType) {
                SoundManager.getInstance(context).playSuccessSound();

                vibtor.vibrate(100);

            } else if (!soundType) {
                SoundManager.getInstance(context).playFailureSound();
                vibtor.vibrate(500);
            }

        }
    }

    /**
     * //Add by wj
     * @param context
     * @param content
     */
    public static void showFilterSoundToast(Context context ,String content){
        Vibrator vibtor = (Vibrator) context
                .getSystemService(Service.VIBRATOR_SERVICE);
        if (content != null && !content.equals("")) {
            Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
            SoundManager.getInstance(context).playFilterSound();
            vibtor.vibrate(500);
        }
    }

    /**
     * 代收货款提示音
     * @param context
     */
    public static void showWaitePaySound(Context context){
        Vibrator vibtor = (Vibrator) context
                .getSystemService(Service.VIBRATOR_SERVICE);
        SoundManager.getInstance(context).playWaitePaySound();
        vibtor.vibrate(500);
    }

    /**
     * 播放提示音
     * @param context
     */
    public static void playSound(Context context){
        Vibrator vibtor = (Vibrator) context
                .getSystemService(Service.VIBRATOR_SERVICE);
        SoundManager.getInstance(context).playFailureSound();
        vibtor.vibrate(500);
    }

    //End by wj

    /**
     * 震动
     *
     * @param context
     */
    public static void vibratorToast(Context context) {
        Vibrator vibtor = (Vibrator) context
                .getSystemService(Service.VIBRATOR_SERVICE);
        vibtor.vibrate(100);

    }

    /**
     * 震动
     *
     * @param context
     * @param milliseconds
     */
    public static void vibratorToast(Context context, int milliseconds) {
        Vibrator vibtor = (Vibrator) context
                .getSystemService(Service.VIBRATOR_SERVICE);
        vibtor.vibrate(milliseconds);

    }

    /**
     * 声音和震动
     *
     * @param context
     */
    public static void showSoundAndVibrator(Context context, boolean soundType) {
        if (soundType == true) {
            SoundManager.getInstance(context).playSuccessSound();
            vibratorToast(context, 100);
        } else if (soundType == false) {
            SoundManager.getInstance(context).playFailureSound();
            vibratorToast(context, 500);
        }

    }

    /**
     * 判断SD卡是否可用
     *
     * @return
     */
    public static boolean iSdCardStatus() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            // sd card 可用
            return true;
        } else {
            // 当前不可用
            return false;
        }
    }

    /**
     * 自定义单选对话框
     *
     * @param context 上下文
     * @param message 内容
     */
    public static void showAlertDialog(Context context, String message) {
        final BaseDialog dialog = new BaseDialog(context);
        dialog.setTitles(message);
        dialog.show();
        dialog.getvCanncel().setVisibility(View.GONE);
        dialog.getvMessage().setVisibility(View.GONE);
        dialog.getvPresentation().setVisibility(View.GONE);
        dialog.getvAccept().setText(R.string.confirm);
        dialog.setOnBackClickListener(new OnBackClickListener() {

            @Override
            public void onBackClickListener(boolean res) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 判断是否为纯数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 登出清除部分数据
     *
     * @param context
     */
    public static void loginOut(Context context) {
        // 登陆信息下载
        LoginInfoManager.getInstance(context).deleteAll();
        // 离线登陆账号信息
        // 下一站网点资料表
        NextSiteManager.getInstance(context).deleteAll();
        TraceUtil.initTrace();
        // 时间同步状态
        StoFilePreference.getInstance(context).setTimeSynch(false);
    }

    /**
     * 将光标设置到末尾
     *
     * @param view
     */
    public static void setCursorEnd(EditText view) {
        view.setSelection(view.getText().toString().length());
    }

    /**
     * 退出提示
     *
     * @param context
     */
    public static void logoutAlert(final Context context) {
        final BaseDialog dialog = new BaseDialog(context);
        dialog.setTitles(context.getText(R.string.change_user).toString());
        dialog.show();
        dialog.getvMessage().setVisibility(View.GONE);
        dialog.getvPresentation().setVisibility(View.GONE);
        dialog.setOnBackClickListener(new OnBackClickListener() {

            @Override
            public void onBackClickListener(boolean res) {
                dialog.dismiss();
                if (res) {
                    Intent logoutIntent = new Intent(context,
                            StoLoginActivity.class);
                    context.startActivity(logoutIntent);
                    ((Activity) context).finish();

                    //	new LogoutThread(context, null, false).start();
                }

            }
        });
    }

    /**
     * 弹框提示
     *
     * @param context
     */
    public static void MsgAlert(final Context context, String text) {
        final BaseDialog dialog = new BaseDialog(context);
        dialog.setTitles(text);
        dialog.show();
        dialog.getvMessage().setVisibility(View.GONE);
        dialog.getvPresentation().setVisibility(View.GONE);
        dialog.setOnBackClickListener(new OnBackClickListener() {

            @Override
            public void onBackClickListener(boolean res) {
                dialog.dismiss();
                if (res) {
                    Intent logoutIntent = new Intent(context,
                            StoLoginActivity.class);
                    context.startActivity(logoutIntent);
                    ((Activity) context).finish();
                }

            }
        });
    }

    /**
     * 清空所有数据
     *
     * @param context
     */
    public static void clearAllData(Context context) {
        // 登陆信息下载
        LoginInfoManager.getInstance(context).deleteAll();
        // 离线登陆账号信息
        // 下一站网点资料表
        NextSiteManager.getInstance(context).deleteAll();
        OrderReturnReasonManager.getInstance(context).deleteAll();
        ProblemManager.getInstance(context).deleteAll();
        BillcodeManager.getInstance(context).deleteAll();
        SalesManager.getInstance(context).deleteAll();
        SiteFullManager.getInstance(context).deleteAll();
        RouteManager.getInstance(context).deleteAll();
        CastManager.getInstance(context).deleteAll();
        SalesSignNameManager.getInstance(context).deleteUserData();
        ServerSmsManager.getInstance(context).deleteAll();
        UserInfoManager.getInstance(context).deleteAll();
        UserManager.getInstance(context).deleteAll();
        UserRuleManager.getInstance(context).deleteAll();
        ErrorRecordManager.getInstance(context).deleteAll();
        OrgRuleManager.getInstance(context).deleteAll();


    }

    /**
     * 清空所有数据
     *
     * @param context
     */
    public static void clearSiteData(Context context) {
        // 登陆信息下载
        LoginInfoManager.getInstance(context).deleteAll();
        // 离线登陆账号信息
        // 下一站网点资料表
        NextSiteManager.getInstance(context).deleteAll();

        // 面单发放
        BillcodeManager.getInstance(context).deleteAll();

        // 面单发放时间
        StoFilePreference.getInstance(context).setBillCodeIssueTime("");

    }

    /**
     * 获取当前应用版本号
     *
     * @param context
     * @return
     * @throws Exception
     * @author mgf
     * @date 2014-02-19
     */
    public static String getVersionName(Context context) {
        String version = "";
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),
                    0);
            version = packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            ExceptionLog.writeLog("getVersionName", e.getMessage());
        }
        return version;
    }

    /**
     * 时间格式转换
     *
     * @param date
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String getStringFromDate(Date date, String formatType) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(formatType);
        return dateFormat.format(date);
    }

    /**
     * 获得七天前的日期 用于到包预报下载首次请求
     *
     * @return
     */
    public static String getBeforeWeekDate() {
        String dateStr = getStringFromDate(getDateBefore(6), DATEFORMAT_PACKET);
        return dateStr.substring(0, 8) + "000000";
    }

    /**
     * 用于下载预报的时间（格式：yyyyMMdd000000）
     *
     * @return
     */
    public static String getTodayForCast() {
        String dateStr = getStringFromDate(new Date(), DATEFORMAT_PACKET);
        return dateStr.substring(0, 8) + "000000";
    }

    /**
     * 得到几天前的时间
     *
     * @param day
     * @return
     */
    public static Date getDateBefore(int day) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DATE, -day);
        return now.getTime();
    }

    /**
     * 将(yyyy-MM-dd)处理时间为(MM-dd-yyyy)
     *
     * @param data
     * @return
     * @author wxf
     */
    public static String changeDataFormat(String data) {
        Date tempdate = new Date();
        SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
        String nowDate = format.format(tempdate);
        String tempData = nowDate;
        try {

            if (data != null && !data.equals("")) {
                String temp = data.substring(0, data.indexOf("-"));
                String temp1 = data.substring(data.indexOf("-") + 1,
                        data.length());
                temp1 += "-" + temp;
                tempData = temp1;
            }

        } catch (Exception e) {
            tempData = nowDate;
        }

        return tempData;
    }

    public static boolean isServiceExisted(Context context, String className) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(Integer.MAX_VALUE);

        if (!(serviceList.size() > 0)) {
            return false;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            RunningServiceInfo serviceInfo = serviceList.get(i);
            ComponentName serviceName = serviceInfo.service;
            if (serviceName.getClassName().equals(className)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 获取错误信息
     *
     * @param ex
     * @return 返回错误信息
     * @throws Exception
     */
    public static String saveCrashInfo2File(Throwable ex) {

        StringBuffer sb = new StringBuffer();

        SimpleDateFormat sDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        sb.append("\r\n" + date + "\n");

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);

        return sb.toString();
    }

    /**
     * 0 gprs 1 wifi
     *
     * @param context
     * @return
     */
    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }

    /**
     * 判断当前网络是否可用
     *
     * @return 如果可用返回true，否则返回false
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager mgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] info = mgr.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取android当前可用内存大小
     *
     * @param c
     * @return
     */
    public static long getAvailMemory(Context c) {//

        return ((MemorySpaceCheck.getInstance().getSDAvailableSize() + MemorySpaceCheck
                .getInstance().getSystemAvailableSize()) / 1024) / 1024;

    }

    /**
     * 获取总内存
     *
     * @param c
     * @return
     */
    public static long getTotalMemory(Context c) {

        return (MemorySpaceCheck.getInstance().getSDTotalSize() + MemorySpaceCheck
                .getInstance().getSysTotalSize()) / (1024 * 1024);

    // String str1 = "/proc/meminfo";// 系统内存信息文件
    // String str2;
    // String[] arrayOfString;
    // long initial_memory = 0;
    //
    // try {
    // FileReader localFileReader = new FileReader(str1);
    // BufferedReader localBufferedReader = new BufferedReader(
    // localFileReader, 8192);
    // str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小
    //
    // arrayOfString = str2.split("\\s+");
    // for (String num : arrayOfString) {
    // Log.i(str2, num + "\t");
    // }
    //
    // initial_memory = Integer.valueOf(arrayOfString[1]).intValue() *
    // 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
    // localBufferedReader.close();
    //
    // } catch (IOException e) {
    // e.printStackTrace();
    // ExceptionLog.writeLog("获取总内存", e.toString());
    // }
    // return (initial_memory / 1024) / 1024 + "";// Byte转换为KB或者MB，内存大小规格化
}

    /**
     * 获取设备类型
     *
     * @return
     */
    public static String getPDAType() {
        if (StoConfig.NEW_DEBUG)
            return "520";
        return Build.MODEL.trim();
    }

    public static boolean isK7(){
        return "K7".equals(Build.MODEL);
    }
    /**
     * 获取android版本
     *
     * @return
     */
    public static String getAndroidOsVersion() {
        String pdaType = getPDAType();
        if ("420".equals(pdaType)) {
            return "2.3.3.0";
        } else if ("585".equals(pdaType)) {
            return "4.0.0.0";
        } else if ("510".equals(pdaType)) {
            return "4.2.2.0";
        } else {
            return "4.4.2.0";
        }
    }

    /**
     * 判断是否为手机号
     * @param phone
     * @return
     */
    public static boolean isMobileNO(String phone){

        if(phone.length()!=11){
            return false;
        }

        return true;

    }
}
